import _ from 'lodash';

const hotUpdateServe = {
  test:
    'http://scm-webrf.oss-cn-hangzhou.aliyuncs.com/TMS/tw-carrefour/retail-store-app/test/version.json',
  pro:
    'http://scm-webrf.oss-cn-hangzhou.aliyuncs.com/TMS/tw-carrefour/retail-store-app/pro/version.json',
};

const data = {
  ttid: 'tw-carrefour',
  cacheList: [],
  baseUrl: 'http://testxa.360scm.com',
  hotUpdateUrl: hotUpdateServe.test,
  mode: 'test',
  isHotUpdate: true,
  serviceList: [
    {
      name: '西安测试',
      url: 'http://testxa.360scm.com',
      type: 'default',
      hotUpdateUrl: hotUpdateServe.test,
      mode: 'test',
    },
    {
      name: 'Timothy',
      url: 'http://172.16.100.52:8999',
      type: 'default',
      hotUpdateUrl: hotUpdateServe.test,
      mode: 'test',
    },
    {
      name: '正式环境',
      url: '',
      type: 'default',
      hotUpdateUrl: hotUpdateServe.pro,
      mode: 'pro',
    },
  ],
  token: '',
};

export const common = {
  namespaced: true,
  state: () => data,
  getters: {
    getCache(state) {
      return state.cacheList;
    },

    getData: (state, getters, rootState) => ({ key, modules }) => {
      return rootState[modules][key];
    },
  },
  mutations: {
    updateData(state, { key, value, rootState, modules }) {
      rootState[modules][key] = value;
    },

    initData(state) {
      for (const i in data) {
        if (Object.prototype.hasOwnProperty.call(data, i)) {
          state[i] = data[i];
        }
      }
    },

    setCache: (state, params) => {
      state.cacheList = params;
    },

    addCache: (state, name) => {
      if (!state.cacheList.some(v => v === name)) {
        state.cacheList = [...state.cacheList, name];
      }
    },

    deleteCache: (state, name) => {
      _.remove(state.cacheList, v => v === name);
    },
  },
  actions: {
    setData({ commit, rootState }, params) {
      params = { ...params, ...{ rootState } };
      commit('updateData', params);
    },

    mapData({ dispatch }, params) {
      params.forEach(v => dispatch('setData', v));
    },
  },
};
